package utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.springframework.util.StringUtils;

public class MachineUtils {
	
	public static final String Windows_Physical_Address = "Physical Address";
	public static final String Linux_HWaddr = "HWaddr";
	public static boolean RTag = false;
	
	/**
	 * 获取机器码
	 * @param os_name
	 * @return
	 */
	public static String getMacAddress(String os_name) {
		if(os_name.toLowerCase().indexOf("windows")>=0)
			return ipconfig().get(Windows_Physical_Address);
		else
			return ifconfig().get(Linux_HWaddr);
	}
	
	/**
	 * Linux ifconfig
	 * @return
	 */
	private static Map<String, String> ifconfig() {
		Map<String, String> infoMap = new HashMap<String, String>();
		try {
			String s1 = "ifconfig";
			Process process = Runtime.getRuntime().exec(s1);
			BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(process.getInputStream()));

			String nextLine;
			for (String line = bufferedreader.readLine(); line != null; line = nextLine) {
				nextLine = bufferedreader.readLine();
				if (!StringUtils.hasText(nextLine))continue;
				if (line.indexOf(Linux_HWaddr) > 0) {
					int i = line.indexOf(Linux_HWaddr) + 7;
					String s = line.substring(i);
					infoMap.put(Linux_HWaddr, s);
				}
			}
			bufferedreader.close();
			process.waitFor();
		} catch (Exception exception) {

		}
		return infoMap;
	}
	
	/**
	 * windows ipconfig
	 * @return
	 */
	private static Map<String, String> ipconfig() {

		Map<String, String> infoMap = new HashMap<String, String>();
		try {
			String s1 = "ipconfig /all";
			Process process = Runtime.getRuntime().exec(s1);
			BufferedReader bufferedreader = new BufferedReader(
					new InputStreamReader(process.getInputStream()));

			String nextLine;
			for (String line = bufferedreader.readLine(); line != null; line = nextLine) {
				nextLine = bufferedreader.readLine();
				if (line.indexOf(Windows_Physical_Address) >= 0) {
					int i = line.indexOf(Windows_Physical_Address) + 36;
					String s = line.substring(i);
					infoMap.put(Windows_Physical_Address, s);
				}
			}

			bufferedreader.close();
			process.waitFor();
		} catch (Exception exception) {
			
		}
		return infoMap;
	}
	
	public static void main(String[] args) throws Exception {
		
	}

}
